<template>
  <el-input v-model="value" :name="name" type="text" @input="onInput" @change="onChange" @blur="onBlur" :placeholder="disabled?'':placeholder" :disabled="disabled"></el-input>
</template>

<script>
  const REG_F = /^[-]?[0-9]*\.?[0-9]*$/
  const REG_Z = /^[0-9]*\.?[0-9]*$/

  export default {
    name:'ComInput',
    props:{
      row:Object,
      name:String,
      placeholder:String,
      disabled:Boolean,
      minin:[Number,String],
      maxin:[Number,String],
      min:[Number,String],
      max:[Number,String],
      fixed:{
        type:[Number,String],
        default:"2"
      }
    },
    data(){
      return {
        value:""
      }
    },
    created(){
      this.value = String(this.row[this.name]||'');
      this.$watch(`row.${this.name}`,(val = "",old)=>{
        if(val != this.value){
          this.value = val;
        }
      })
    },
    methods:{
      onInput(val) {
        // 正则表达式只允许输入数字、负号和小数点
        const regex = this.minin < 0 ? REG_F : REG_Z;
        if (!regex.test(val)) {
          this.value = this.row[this.name];
          return;
        }

        const min = this.min;
        const max = this.max;
        const minin = this.minin;
        const maxin = this.maxin || 999999999;
        // 最小值
        if(min !== void 0 && parseFloat(val)<parseFloat(min)){
          this.value = this.row[this.name];
          return;
        }
        if(minin !== void 0 && parseFloat(val)<parseFloat(minin)){
          this.setValue(minin);
          return;
        }
        // 最大值
        if(max !== void 0 && parseFloat(val)>parseFloat(max)){
          this.value = this.row[this.name];
          return;
        }
        if(maxin !== void 0 && parseFloat(val)>parseFloat(maxin)){
          this.setValue(maxin);
          return;
        }
        // 小数位
        let fixed = this.fixed;
        let valArr = val.split(".");
        let fixStr = valArr[1]||'';
        if(fixed == 0){
          val = valArr[0];
        }else if(fixStr.length>fixed){
          val = val.substr(0,val.length - (fixStr.length - fixed));
        }
        this.setValue(val);
      },
      onChange(){
        this.$emit("change",this.value);
      },
      onBlur(){
        // if(String(this.value||'').trim() === "" && this.minin){
        //   this.setValue(String(this.minin))
        // }
      },
      setValue(val = ''){
        this.value = String(val);
        this.row[this.name] = this.value;
        this.$emit("keyup",this.value);
      }
    }
  }
</script>
